## package vocab

window.vocab = {}

## private

LANGUAGE_TO_ENGLISH = 0
ENGLISH_TO_LANGUAGE = 1
SPOKEN_TO_ENGLISH = 2

# Properties

$vocab = []

$selected_row_ids = []

$vocab_list = null
$vocab_carousel = null
$data_view = null
$grid = null
$sort_direction = 1
$sort_column = 'co'
$canvas_width = undefined
$canvas_height = undefined

$test_type = null
$questions = null
$time_per_question = null
$percent_correct = null
$number_questions = null
$current_question = null
$answer_regex = null
$timeout_timer = null
$time_remaining = null
$test_ended = false

# Hack so that the grid doesn't display on top of all the vocab
$grid_hidden = false

$current_question_text = null
$total_questions_text = null
$percent_correct_text = null
$question_text = null
$answer_box = null
$time_display = null

init_properties = ->
  $current_question_text = $('#vocab-qnumber')
  $total_questions_text = $('#vocab-qtotal')
  $percent_correct_text = $('#vocab-percent')
  $question_text = $('#vocab-question')
  $answer_box = $('#vocab-answer')
  $time_display = $('#vocab-time')

# Canvas

load_canvas_data = (vocab, required_length = 20) ->
  data = []
  for i in [0..10]
    percent = i * 10
    filtered_vocab = _.filter vocab, (item) -> item.pr == percent
    for v in filtered_vocab
      data.push "#{v.co} - #{v.tr}"
      break if data.length is required_length
    break if data.length is required_length
  until data.length is required_length
    v = vocab[rand(vocab.length)]
    data.push "#{v.co} - #{v.tr}"
  data_list = $ '#vocab-canvas-data'
  for item in data
    element = $ '<li><a>#{data}</a></li>'
    data_list.append element

show_canvas = ->
  canvas = $('#vocab-canvas')
  $canvas_width = canvas.offsetWidth
  $canvas_height = canvas.offsetHeight
  max_speed = if app.OLD_IE then 0 else 0.02
  initial_speed = if app.OLD_IE then 0 else 0.05
  #TODO: Why .width and attr(width) ?
  canvas.width($canvas_width).height($canvas_height).attr("width",$canvas_width).attr("height",$canvas_height).tagcanvas {
    textFont: 'Maven Pro, sans-serif'
    textColour: '#ffffff'
    outlineMethod: 'outline'
    outlineColour: 'rgba(255,255,255,0)'
    reverse: on
    depth: 2
    maxSpeed: max_speed
    initial: [init_speed, 0]
    shape: 'vcylinder'
    lock: 'x'
  }, 'vocab-canvas-data'

load_canvas = (data) ->
  required_length = Math.floor($('#vocab-canvas')[0].offsetWidth / 50)
  load_canvas_data data, required_length
  show_canvas()

# Grid Utility

int_comparer = (a, b) ->
  x = a[$sort_column]
  y = b[$sort_column]
  if x == y then 0 else if x > y then 1 else -1

#TODO: Is this too slow on IE? If so, see SlickGrid dataview example
string_comparer = (a,b) ->
  x = a[$sort_column].toLowerCase()
  y = b[$sort_column].toLowerCase()
  x = x.replace /^\(.+\)\s*/, ""
  y = y.replace /^\(.+\)\s*/, ""
  if x == y then 0 else if x > y then 1 else -1

grid_filter = (item, args) ->
  if args.category != "" and $.inArray args.category, item.ca
    return false
  if args.string != "" and item.co.indexOf(args.string) == -1 and item.tr.indexOf(args.string) == -1
    return false
  return true

update_grid_filter = (category="") ->
  #TODO: Add textbox to set string filter
  $data_view.setFilterArgs { category: category, string: "" }
  $data_view.refresh()

load_grid = (data) ->
  columns = [
    { id: "lang", name: login.language_name, field: "co", sortable: true },
    { id: "eng", name: "English", field: "tr", sortable: true },
    {
      id: "prog", name: "Progress", field: "pr", width: 100, resizable: false, sortable: true,
      formatter: GraphicalPercentCompleteCellFormatter
    }
  ]
  options =
    enableCellNavigation: true
    enableColumnReorder: false
    forceFitColumns: true
  $data_view = new Slick.Data.DataView()
  $grid = new Slick.Grid "#vgrid", $data_view, columns, options
  $grid.setSelectionModel new Slick.RowSelectionModel()
  $grid.onSort.subscribe (e, args) ->
    $sort_direction = if args.sortAsc then 1 else -1
    $sort_column = args.sortCol.field
    if $sort_column == "pr"
      $data_view.sort int_comparer, args.sortAsc
    else
      $data_view.sort string_comparer, args.sortAsc
  $grid.onSelectedRowsChanged.subscribe (e) ->
    $selected_row_ids = []
    rows = $grid.getSelectedRows()
    for row in rows
      item = $data_view.getItem row
      if item then $selected_row_ids.push item.id
  $data_view.onRowCountChanged.subscribe (e,args) ->
    $grid.updateRowCount()
    $grid.render()
  $data_view.onRowsChanged.subscribe (e,args) ->
    $grid.invalidateRows args.rows
    $grid.render()
    if $selected_row_ids.length > 0
      # since the way the original data maps onto rows has changed,
      # the selected rows in the grid need to be updated
      selRows = []
      for row in $selected_row_ids
        idx = $data_view.getRowById row
        if idx != undefined
          selRows.push idx
      $grid.setSelectedRows selRows
  $data_view.beginUpdate()
  $data_view.setItems vocab.loaded_vocab
  $data_view.sort string_comparer, true
  $data_view.setFilterArgs { category: "", string: "" }
  $data_view.setFilter grid_filter
  $data_view.endUpdate()

## public

vocab.load = (data) ->
  $vocab = data
  load_canvas data
  load_grid data

## initialize

vocab.initialize = ->
  # pass
